package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
	"tomato-novel/cache"
	"tomato-novel/model"
)

func List(c *gin.Context) {

	/*
		SELECT
		tomatoes.us_id as UsId,
		tomatoes.title as Title,
		tomatoes.comment as Comment,
		tomatoes.author as Author,
		users.username as Username,
		users.password as Password,
		FROM
		tomatoes
		LEFT JOIN users on tomatoes.us_id = users.id
	*/

	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))

	offset := (page - 1) * size

	var tomato []model.TomatoUser
	redis_key := "tomato_list" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Table("tomatoes").Select(
			"tomatoes.us_id as UsId",
			"tomatoes.title as Title",
			"tomatoes.comment as Comment",
			"tomatoes.author as Author",
			"users.username as Username",
			"users.password as Password",
		).Joins("LEFT JOIN users on tomatoes.us_id = users.id").Offset(offset).Limit(size).Debug().Find(&tomato)
		jsonData, _ := json.Marshal(tomato)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &tomato)
	}

	var total int64
	model.DB.Model(&model.Tomato{}).Count(&total)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "展示成功",
		"data":  tomato,
		"total": total,
	})
}

func Detail(c *gin.Context) {
	id := c.Query("id")

	var tomato model.Tomato
	redis_key := "tomato_list" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Where("id=?", id).Debug().First(&tomato)
		jsonData, _ := json.Marshal(tomato)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &tomato)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "展示成功",
		"data": tomato,
	})

}
